<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="JkProductForm">
          <a-row>
						<a-col :span="24">
							<a-form-item label="产品名称" v-bind="validateInfos.productname" id="JkProductForm-productname" name="productname">
								<a-input v-model:value="formData.productname" placeholder="请输入产品名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="24">
              <a-form-item label="版本号" v-bind="validateInfos.version" id="JkProductForm-version" name="version">
                <a-input v-model:value="formData.version" placeholder="请输入版本号"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
						<a-col :span="24">
							<a-form-item label="产品类型" v-bind="validateInfos.producttype" id="JkProductForm-producttype" name="producttype">
								<j-select-multiple type="list_multi" v-model:value="formData.producttype" dictCode="product_type" placeholder="请选择产品类型"  :triggerChange="false"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="关联企业" v-bind="validateInfos.companyid" id="JkProductForm-companyid" name="companyid">
								<j-select-multiple type="list_multi" v-model:value="formData.companyid" dictCode="jk_company,name,id" placeholder="请选择关联企业"  :triggerChange="false"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="图片" v-bind="validateInfos.imageurl" id="JkProductForm-imageurl" name="imageurl">
								<j-image-upload :fileMax="0" v-model:value="formData.imageurl" ></j-image-upload>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="核心技术文档" v-bind="validateInfos.videourl" id="JkProductForm-videourl" name="videourl">
								<j-upload v-model:value="formData.videourl"   ></j-upload>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品规格描述" v-bind="validateInfos.productspecification" id="JkProductForm-productspecification" name="productspecification">
								<a-textarea v-model:value="formData.productspecification" :rows="2" placeholder="请输入产品规格描述" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品评分" v-bind="validateInfos.productrating" id="JkProductForm-productrating" name="productrating">
								<a-input-number v-model:value="formData.productrating" placeholder="请输入产品评分，最多两位小数（如4.50）" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品详细介绍" v-bind="validateInfos.productdetails" id="JkProductForm-productdetails" name="productdetails">
                <a-textarea v-model:value="formData.productdetails"  :rows="3" placeholder="请输入产品详细介绍"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="成果内容描述" v-bind="validateInfos.achievementcontent" id="JkProductForm-achievementcontent" name="achievementcontent">
								<j-editor v-model:value="formData.achievementcontent"  :autoFocus="false"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品价格" v-bind="validateInfos.price" id="JkProductForm-price" name="price">
								<a-input-number v-model:value="formData.price" placeholder="请输入产品价格" style="width: 100%" />
							</a-form-item>
						</a-col>

						<a-col :span="24">
							<a-form-item label="相关论文" v-bind="validateInfos.paperid" id="JkProductForm-paperid" name="paperid">
								<j-select-multiple type="list_multi" v-model:value="formData.paperid" dictCode="jk_papers,paper_title,id" placeholder="请选择相关论文"  :triggerChange="false"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="相关专利" v-bind="validateInfos.patentid" id="JkProductForm-patentid" name="patentid">
								<j-select-multiple type="list_multi" v-model:value="formData.patentid" dictCode="jk_patent_info,patent_title,id" placeholder="请选择相关专利"  :triggerChange="false"/>
							</a-form-item>
						</a-col>


            <a-col :span="24">
              <a-form-item label="产品型号" v-bind="validateInfos.productModel" id="JkProductForm-productModel" name="productModel">
                <a-input v-model:value="formData.productModel" placeholder="请输入产品型号"  allow-clear ></a-input>
              </a-form-item>
            </a-col>


            <a-col :span="24">
              <a-form-item label="技术参数" v-bind="validateInfos.technicalSpecifications" id="JkProductForm-technicalSpecifications" name="technicalSpecifications">
                <a-input v-model:value="formData.technicalSpecifications" placeholder="请输入技术参数"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="轮播图状态" v-bind="validateInfos.slider" id="JkProductForm-slider" name="slider">
                <j-dict-select-tag type='radio' v-model:value="formData.slider" dictCode="slider_status" placeholder="请选择轮播图状态"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="产品状态" v-bind="validateInfos.productStatus" id="JkProductForm-productStatus" name="productStatus">
                <j-dict-select-tag v-model:value="formData.productStatus" dictCode="product_status" placeholder="请选择产品状态"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="上架状态" v-bind="validateInfos.isavailable" id="JkProductForm-isavailable" name="isavailable">
                <j-dict-select-tag type='radio' v-model:value="formData.isavailable" dictCode="isavailable" placeholder="请选择是否上架"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="排序" v-bind="validateInfos.sn" id="JkCompanyForm-sn" name="sn">
                <a-input v-model:value="formData.sn" placeholder="请输入序列号"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../JkProduct.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    productname: '',   
    producttype: '',   
    companyid: '',   
    imageurl: '',   
    videourl: '',   
    productspecification: '',   
    productrating: undefined,
    productdetails: '',   
    achievementcontent: '',   
    price: undefined,
    isavailable: '',   
    paperid: undefined,
    patentid: undefined,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    productname: [{ required: true, message: '请输入产品名称，不能为空!'},],
    companyid: [{ required: true, message: '请输入公司ID，关联公司信息!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
